package com.quxing.amazon.security;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.quxing.amazon.model.dto.UserBasicInfo;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhb
 * @description
 * @date 2020/11/27 16:44
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class JwtUser implements UserDetails {

    /**
     * 主键
     */
    private Integer id;

    /**
     * 用户名
     */
    private String username;

    /**
     * 密码
     */
    private String password;


    /**
     * 用户权限列表
     */
    private Collection<? extends GrantedAuthority> authorities;

    public static JwtUser create(UserBasicInfo user) {
        List<CustomGrantedAuthority> authorities = user.getRoles()
                .stream()
                .map(CustomGrantedAuthority::new)
                .collect(Collectors.toList());
        return new JwtUser(user.getId(), user.getUsername(), user.getPassword(), authorities);
    }


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isEnabled() {
        return true;
    }

}
